package com.emm.yixun.mobile.ui.analysis;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainProjectAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetCustomerAnalysisList;
import com.emm.yixun.mobile.model.GetCustomerVisitAnalysisList;
import com.emm.yixun.mobile.model.GetProjectList;
import com.emm.yixun.mobile.model.GetProjectList.ProjectList;
import com.eroad.product.tools.PickerView;
import com.eroad.product.tools.PickerView.onSelectListener;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.PercentFormatter;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * 
 * <p>
 * <b>Title：</b> 客户分析
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午4:10:16
 */
public class CustomerAnalysisActivity extends SwipeBackActivity implements OnChartValueSelectedListener {

	private static final String TAG = "CustomerAnalysisActivity";

	/** 扇形图 */
	private PieChart mChart;

	TextView null_date1, null_date2;

	/** 数据列表 */
	private ArrayList<String> list = new ArrayList<String>();

	/** 数据列表每项所对应的百分比 */
	private ArrayList<Float> list2 = new ArrayList<Float>();

	/** 顶部类目 */
	TextView set_type;

	/** 类目布局模块 */
	LinearLayout sort_textview;

	/** 类目箭头 */
	ImageView icon1;

	/** 顶部日期模块 */
	LinearLayout screen_textview;

	/** 顶部日期 */
	TextView colors_text2;

	/** 日期箭头 */
	ImageView icon2;

	View viewproject;
	PopupWindow popuproject;

	/** 选中的类型 */
	private int SelectPostion = 0;

	/** title_main */
	TextView title_main;

	/** 返回按钮 */
	ImageView back_btn;

	/** 日期选择显示类容 */
	TextView set_content;

	/** 打开日期选择 */
	LinearLayout open_layout;

	/* ---公用选择框--- */
	View view;
	PopupWindow popu;
	/** 选中内容 */
	String selectName;
	/** 选中下标 */
	int SelectID;
	ArrayList<String> listname;
	/* ---公用选择框--- */

	/** 侧滑关闭框架 */
	private SwipeBackLayout mSwipeBackLayout;

	/** 折线图 */
	LinearLayout linear;

	ArrayList<Integer> bgcolor = new ArrayList<Integer>();

	@Override
	protected void onResume() {
		BaseActivity.activity = this; // TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化统计图的颜色
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:53:01
	 */
	private void SetColor() {
		bgcolor.add(Color.parseColor("#FFE76E"));
		bgcolor.add(Color.parseColor("#FFC499"));
		bgcolor.add(Color.parseColor("#FFB468"));
		bgcolor.add(Color.parseColor("#FF9048"));
		bgcolor.add(Color.parseColor("#F64A2A"));
		bgcolor.add(Color.parseColor("#FA7388"));
		bgcolor.add(Color.parseColor("#F63C7F"));
		bgcolor.add(Color.parseColor("#F43560"));
		bgcolor.add(Color.parseColor("#CC1F1A"));
		bgcolor.add(Color.parseColor("#740D0C"));
		bgcolor.add(Color.parseColor("#C6F4FF"));
		bgcolor.add(Color.parseColor("#67C3D5"));
		bgcolor.add(Color.parseColor("#5199AA"));
		bgcolor.add(Color.parseColor("#009796"));
		bgcolor.add(Color.parseColor("#009868"));
		bgcolor.add(Color.parseColor("#8CD3E7"));
		bgcolor.add(Color.parseColor("#1FBBD3"));
		bgcolor.add(Color.parseColor("#006EA8"));
		bgcolor.add(Color.parseColor("#005AA6"));
		bgcolor.add(Color.parseColor("#5B5377"));
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cutomer_analysis_activity);

		SetSwipeBackLayout(mSwipeBackLayout);

		BaseActivity.activity = this;
		SetColor();
		initView();
		initBtn();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化view
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:54:08
	 */
	private void initView() {
		mChart = (PieChart) findViewById(R.id.chart1);
		mChart.setNoDataText(" ");
		set_type = (TextView) findViewById(R.id.set_type);
		sort_textview = (LinearLayout) findViewById(R.id.sort_textview);
		icon1 = (ImageView) findViewById(R.id.icon1);
		screen_textview = (LinearLayout) findViewById(R.id.screen_textview);
		colors_text2 = (TextView) findViewById(R.id.colors_text2);
		icon2 = (ImageView) findViewById(R.id.icon2);
		title_main = (TextView) findViewById(R.id.title_main);
		title_main.setText(getString(R.string.analysis_title));
		back_btn = (ImageView) findViewById(R.id.back_btn);
		set_content = (TextView) findViewById(R.id.set_content);
		open_layout = (LinearLayout) findViewById(R.id.open_layout);
		linear = (LinearLayout) findViewById(R.id.linear);
		null_date1 = (TextView) findViewById(R.id.null_date1);
		null_date2 = (TextView) findViewById(R.id.null_date2);
		SetRelativiLayoutPadding(R.id.main_head_top_rela);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化监听事件
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:54:43
	 */
	private void initBtn() {
		getCustomerAnalysisList("1", "1");
		getCustomerVisitAnalysisList("1");
		sort_textview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				set_type.setTextColor(Color.parseColor("#FD593E"));
				colors_text2.setTextColor(Color.parseColor("#3E3C3D"));
				icon1.setImageResource(R.drawable.paixu_down);
				icon2.setImageResource(R.drawable.paixu_up);
				SetsortPopu(set_type, 0);
			}
		});

		screen_textview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				set_type.setTextColor(Color.parseColor("#3E3C3D"));
				colors_text2.setTextColor(Color.parseColor("#FD593E"));
				icon1.setImageResource(R.drawable.paixu_up);
				icon2.setImageResource(R.drawable.paixu_down);
				SetsortPopu(colors_text2, 1);
			}
		});
		back_btn.setVisibility(View.VISIBLE);
		back_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		open_layout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				listname = new ArrayList<String>();
				listname.add("近7天");
				listname.add("近15天");
				listname.add("近一月");
				listname.add("近三月");
				listname.add("近半年");
				SetzpPopu(listname, "时间筛选", set_content);
			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 配置扇形图属性,第一次在加载数据完成之后触发
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param type
	 * @author tangxin
	 * @date 2016年12月7日 上午11:56:34
	 */
	private void SetSettingChart(int type) {
		mChart.setUsePercentValues(true);
		mChart.setHoleColorTransparent(true);
		mChart.setHoleRadius(EmmApplication.dip2px(25));
		mChart.setTransparentCircleRadius(EmmApplication.dip2px(27));
		if (type == 0) {
			mChart.setHoleColor(Color.parseColor("#ffffff"));
			mChart.setCenterText("100%");
		} else {
			mChart.setHoleColor(Color.parseColor("#00ffffff"));
			mChart.setCenterText(" ");
		}
		mChart.setDescription("");
		mChart.setDrawCenterText(true);
		mChart.setDrawHoleEnabled(true);
		mChart.setRotationAngle(0);
		mChart.setRotationEnabled(true);
		mChart.setOnChartValueSelectedListener(this);
		mChart.setX(EmmApplication.dip2px(-50));
		mChart.setExtraOffsets(0.f, 0.f, 50.f, 0.f);
		setData();
		mChart.animateXY(1000, 1000);
		Legend l = mChart.getLegend();
		l.setPosition(LegendPosition.RIGHT_OF_CHART);
		l.setXEntrySpace(200f);
		l.setYEntrySpace(1f);
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 给新的数据绘制 扇形图
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:56:47
	 */
	private void SetChartDate() {
		setData();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 调用动画效果
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:56:53
	 */
	private void animate() {
		mChart.invalidate();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 给统计图配置数据
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 上午11:57:00
	 */
	private void setData() {
		ArrayList<Entry> yVals1 = new ArrayList<Entry>();
		for (int i = 0; i < list2.size(); i++) {
			yVals1.add(new Entry(list2.get(i), i));
		}
		ArrayList<String> xVals = new ArrayList<String>();

		PieDataSet dataSet = new PieDataSet(yVals1, "");
		dataSet.setSliceSpace(3f);
		for (int i = 0; i < list.size(); i++)
			xVals.add(list.get(i) + ("(" + list2.get(i) + "%" + ")"));
		dataSet.setDrawValues(false);
		mChart.setDrawSliceText(false);
		ArrayList<Integer> colors = new ArrayList<Integer>();

		for (int i = 0; i < list.size(); i++) {
			colors.add(bgcolor.get(i));
		}

		dataSet.setColors(colors);
		PieData data = new PieData(xVals, dataSet);
		data.setValueFormatter(new PercentFormatter());
		data.setValueTextSize(11f);
		data.setValueTextColor(Color.BLACK);
		mChart.setData(data);
		mChart.highlightValues(null);
		mChart.setNoDataTextDescription(" ");
		mChart.invalidate();
	}

	public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
		if (e == null)
			return;
		Log.i("VAL SELECTED", "Value: " + e.getVal() + ", xIndex: " + e.getXIndex() + ", DataSet index: "
				+ dataSetIndex);
	}

	public void onNothingSelected() {
		Log.i("PieChart", "nothing selected");
	}

	/** 时间类型 */
	int timeTypeCount = 0;

	/** 类目类型 */
	int categoryTypeCount = 0;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 条件切换弹出框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param tv
	 * @param type
	 * @author tangxin
	 * @date 2016年12月7日 上午11:59:13
	 */
	public void SetsortPopu(final TextView tv, final int type) {
		viewproject = LayoutInflater.from(CustomerAnalysisActivity.this).inflate(R.layout.mainproject_popu, null);
		popuproject = new PopupWindow(viewproject, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popuproject.setFocusable(true);
		popuproject.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popuproject.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popuproject.showAtLocation(sort_textview, Gravity.TOP, 0, 0);
		popuproject.setFocusable(true);
		popuproject.setOutsideTouchable(true);
		viewproject.setFocusable(true);
		viewproject.setFocusableInTouchMode(true);
		viewproject.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popuproject.dismiss();
					EmmApplication.setLog(CustomerAnalysisActivity.this);
				}
				return false;
			}
		});
		viewproject.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popuproject.dismiss();
				EmmApplication.setLog(CustomerAnalysisActivity.this);
			}
		});
		ListView popu_list = (ListView) viewproject.findViewById(R.id.popu_list);
		RelativeLayout top_relativelayout = (RelativeLayout) viewproject.findViewById(R.id.top_relativelayout);
		SetViewPaddingHeight(top_relativelayout, 95);
		final GetProjectList list = new GetProjectList();
		ArrayList<ProjectList> ll = new ArrayList<ProjectList>();

		if (type == 0) {
			ProjectList m = new ProjectList();
			m.setProjectCode("1");
			m.setProjectName("意向等级");
			ll.add(m);

			ProjectList m2 = new ProjectList();
			m2.setProjectCode("2");
			m2.setProjectName("关注户型");
			ll.add(m2);

			ProjectList m3 = new ProjectList();
			m3.setProjectCode("3");
			m3.setProjectName("需求面积");
			ll.add(m3);

			ProjectList m4 = new ProjectList();
			m4.setProjectCode("4");
			m4.setProjectName("预算总价");
			ll.add(m4);

			ProjectList m5 = new ProjectList();
			m5.setProjectCode("5");
			m5.setProjectName("客户年龄");
			ll.add(m5);

			ProjectList m6 = new ProjectList();
			m6.setProjectCode("6");
			m6.setProjectName("客户状态");
			ll.add(m6);
		} else {

			ProjectList m = new ProjectList();
			m.setProjectCode("1");
			m.setProjectName("今天");
			ll.add(m);

			ProjectList m2 = new ProjectList();
			m2.setProjectCode("2");
			m2.setProjectName("昨天");
			ll.add(m2);

			ProjectList m3 = new ProjectList();
			m3.setProjectCode("3");
			m3.setProjectName("本周");
			ll.add(m3);

			ProjectList m4 = new ProjectList();
			m4.setProjectCode("4");
			m4.setProjectName("上周");
			ll.add(m4);

			ProjectList m5 = new ProjectList();
			m5.setProjectCode("5");
			m5.setProjectName("本月");
			ll.add(m5);

			ProjectList m6 = new ProjectList();
			m6.setProjectCode("6");
			m6.setProjectName("上月");
			ll.add(m6);

			ProjectList m7 = new ProjectList();
			m7.setProjectCode("7");
			m7.setProjectName("近三月");
			ll.add(m7);

			ProjectList m8 = new ProjectList();
			m8.setProjectCode("8");
			m8.setProjectName("今年");
			ll.add(m8);
		}
		list.setProjectList(ll);
		MainProjectAdapter adapter = new MainProjectAdapter(CustomerAnalysisActivity.this, list);
		popu_list.setAdapter(adapter);
		if (type == 0) {
			if (list.getProjectList().size() >= (categoryTypeCount + 1)) {
				adapter.SeleCt(categoryTypeCount);
				popu_list.setSelection(categoryTypeCount);
				tv.setText(list.getProjectList().get(categoryTypeCount).getProjectName());
			} else {
				adapter.SeleCt(0);
				popu_list.setSelection(0);
				tv.setText(list.getProjectList().get(0).getProjectName());
			}
		} else {
			if (list.getProjectList().size() >= (timeTypeCount + 1)) {
				adapter.SeleCt(timeTypeCount);
				popu_list.setSelection(timeTypeCount);
				tv.setText(list.getProjectList().get(timeTypeCount).getProjectName());
			} else {
				adapter.SeleCt(0);
				popu_list.setSelection(0);
				tv.setText(list.getProjectList().get(0).getProjectName());
			}
		}
		adapter.SetType(1);
		popu_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				SelectPostion = position;
				popuproject.dismiss();
				EmmApplication.setLog(CustomerAnalysisActivity.this);
				tv.setText(list.getProjectList().get(position).getProjectName());
				if (type == 0) {// 类目类型
					categoryTypeCount = position;
				} else {// 时间类型
					timeTypeCount = position;
				}
				Log.v(TAG, "timeTypeCount:" + timeTypeCount + "/-->categoryTypeCount:" + categoryTypeCount);
				getCustomerAnalysisList("" + (timeTypeCount + 1), "" + (categoryTypeCount + 1));

			}
		});
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 选项框
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param listname
	 * @param title
	 * @param ed
	 * @author tangxin
	 * @date 2016年12月7日 下午12:01:55
	 */
	@SuppressLint("WrongConstant")
	public void SetzpPopu(final List<String> listname, String title, final TextView ed) {
		view = LayoutInflater.from(CustomerAnalysisActivity.this).inflate(R.layout.popu_zp, null);
		popu = new PopupWindow(view, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
				android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
		popu.setFocusable(true);
		// EmmApplication.setNumberLog(CustomerAnalysisActivity.this, 0.5f);//
		// 改变popupwindow范围外的屏幕亮度
		popu.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
		popu.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		popu.showAtLocation(view, Gravity.BOTTOM, 0, 0);
		popu.showAsDropDown(view, 0, 0);
		popu.setFocusable(true);
		popu.setOutsideTouchable(true);
		view.setFocusable(true);
		view.setFocusableInTouchMode(true);
		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					popu.dismiss();
					EmmApplication.setLog(CustomerAnalysisActivity.this);
				}
				return false;
			}
		});
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				popu.dismiss();
				EmmApplication.setLog(CustomerAnalysisActivity.this);
			}
		});

		PickerView select_pick = (PickerView) view.findViewById(R.id.select_pick);

		selectName = listname.get(0);

		TextView shuerbtn = (TextView) view.findViewById(R.id.shuerbtn);
		RelativeLayout relative_all = (RelativeLayout) view.findViewById(R.id.relative_all);

		ImageView dis_btn = (ImageView) view.findViewById(R.id.dis_btn);
		dis_btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popu.dismiss();
				EmmApplication.setLog(CustomerAnalysisActivity.this);
			}
		});
		TextView title_select = (TextView) view.findViewById(R.id.title_select);

		title_select.setText(title);

		select_pick.setData(listname);
		select_pick.setOnSelectListener(new onSelectListener() {
			@Override
			public void onSelect(String text, int id) {
				selectName = text;
				SelectID = id;
			}
		});
		select_pick.setSelected(0);
		shuerbtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 确定
				popu.dismiss();
				EmmApplication.setLog(CustomerAnalysisActivity.this);
				ed.setText(selectName);
				Log.v(TAG, "SelectID-->" + SelectID);
				// ：1、近7天（默认）；2、近15天；3、近一月；4、近三月；5、近半年
				String timetype = "";
				if (selectName.equals("近7天")) {
					timetype = "" + 1;
				} else if (selectName.equals("近15天")) {
					timetype = "" + 2;
				} else if (selectName.equals("近一月")) {
					timetype = "" + 3;
				} else if (selectName.equals("近三月")) {
					timetype = "" + 4;
				} else if (selectName.equals("近半年")) {
					timetype = "" + 5;
				}

				getCustomerVisitAnalysisList(timetype);
			}
		});
		relative_all.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
	}

	XYMultipleSeriesDataset mDataset;
	XYSeries series;

	ArrayList<String> pageperature = new ArrayList<String>();
	ArrayList<String> mt = new ArrayList<String>();

	XYMultipleSeriesRenderer mRenderer;
	XYSeriesRenderer r;

	int Min = 0;
	int Max = 10;
	int XMax = 6;

	int year = 2016;
	int Month = 5;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 初始化线状图
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午12:02:15
	 */
	private void lineView() {
		// 同样是需要数据dataset和视图渲染器renderer
		mDataset = new XYMultipleSeriesDataset();
		series = new XYSeries("客户来访统计趋势");
		// 可以通过循环，多个添加点的数据
		for (int i = 0; i < pageperature.size(); i++) {
			series.add(i + 1, Double.valueOf(pageperature.get(i)).doubleValue());
		}
		mDataset.addSeries(series);

		initViewRenderer();
		SetView();
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 将折线图绘制到view上
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午1:58:07
	 */
	private void SetView() {
		view = ChartFactory.getLineChartView(CustomerAnalysisActivity.this, mDataset, mRenderer);// 调用Achartengine包创建一个折线View
		view.setBackgroundColor(Color.parseColor("#ffffff"));// 折线图背景色
		view.setPadding(10, 20, 10, 10);// 折线图View与其父类边距
		linear.removeAllViews();
		linear.addView(view);// linear是一个装View的布局容器
	}

	// 最小值
	public static double getMin(double[] temperature) {
		double min = temperature[0];
		for (int x = 1; x < temperature.length; x++) {
			if (min > temperature[x]) {
				min = temperature[x];
			}
		}
		return min;
	}

	// 得最大值
	public static double getMax(double[] arr) {
		double max = arr[0];
		for (int x = 1; x < arr.length; x++) {
			if (max < arr[x]) {
				max = arr[x];
			}
		}
		return max;
	}

	// 平均值
	public static double getMean(double[] str) {
		double mMean = 0;
		double num = 0;
		for (int i = 0; i < str.length; i++) {
			num += str[i];
		}
		mMean = num / str.length;
		return mMean;
	}

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 配置统计图属性
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @author tangxin
	 * @date 2016年12月7日 下午1:58:31
	 */
	private void initViewRenderer() {
		mRenderer = new XYMultipleSeriesRenderer();
		// 设置图表的X轴的当前方向
		mRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
		mRenderer.setAxisTitleTextSize(EmmApplication.sp2px(11));// 设置轴标题文本大小
		mRenderer.setChartTitleTextSize(EmmApplication.sp2px(11));// 设置图表标题文字的大小
		mRenderer.setLabelsTextSize(EmmApplication.sp2px(10));// 设置标签的文字大小
		mRenderer.setLegendTextSize(EmmApplication.sp2px(10));// 设置图例文本大小
		mRenderer.setPointSize(8f);// 设置点的大小
		mRenderer.setYAxisMin(Min);// 设置y轴最小值
		mRenderer.setYAxisMax(Max);// 最大值
		mRenderer.setYLabels(10);// 设置Y轴刻度个数（貌似不太准确）
		mRenderer.setXAxisMax(5);// 设置X轴最大值（数值越大，X轴刻度越密集）
		mRenderer.setXAxisMin(0.5);
		mRenderer.setShowGrid(true);// 显示网格
		mRenderer.setZoomButtonsVisible(false);// 是否显示放大缩小按钮
		// mRenderer.setPanLimits(new double[] { 0, Max, 10, XMax }); //
		// 设置拖动时X轴Y轴允许的最大值最小值.
		mRenderer.setXLabelsColor(Color.parseColor("#D3D3D3")); // X Y轴刻度颜色
		mRenderer.setYLabelsColor(0, Color.parseColor("#D3D3D3"));
		mRenderer.setGridColor(Color.parseColor("#F6F7F6"));// 设置网格颜色
		mRenderer.setAxesColor(Color.parseColor("#00767676"));// 设置坐标轴颜色
		for (int i = 0; i < mt.size(); i++) {
			mRenderer.addXTextLabel(i + 1, mt.get(i));
		}
		mRenderer.setXLabels(0);// 设置只显示如1月，2月等替换后的东西，不显示1,2,3等
		mRenderer.setMargins(new int[] { EmmApplication.dip2px(10), EmmApplication.dip2px(15), EmmApplication.dip2px(10),
				EmmApplication.dip2px(10) });// 设置视图位置
		mRenderer.setPointSize(6f);// 设置点的值
		mRenderer.setApplyBackgroundColor(true);// 是否设置外层View背景色
		mRenderer.setBackgroundColor(Color.parseColor("#ffffff"));// 网格背景色
		mRenderer.setMarginsColor(Color.parseColor("#ffffff"));// 外层View背景色，下面是官方注释，上面是我的理解注释
		// 背景色设置需要设置两项：setMarginsColor（设置四边颜色）以及setBackgroundColor（设置中间背景色）
		// 设置背景图片：
		mRenderer.setPanEnabled(true, false); // 设置X Y轴是否能够被拖动(前X 后Y)
		r = new XYSeriesRenderer();// (类似于一条线对象)
		r.setColor(Color.parseColor("#54ACEC"));// 设置颜色
		r.setPointStyle(PointStyle.CIRCLE);// 设置点的样式
		r.setFillPoints(false);// 填充点（显示的点是空心还是实心）
		r.setDisplayChartValues(true);// 将点的值显示出来
		r.setChartValuesSpacing(10);// 显示的点的值与图的距离
		r.setChartValuesTextSize(EmmApplication.sp2px(10));// 点的值的文字大小
		r.setLineWidth(2);// 设置线宽
		mRenderer.addSeriesRenderer(r);
	}

	public static int getDayOfMonth() {// 从系统调用Calendar获取当前月份的天数，用来绘制X轴的刻度数目
		Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
		int day = aCalendar.getActualMaximum(Calendar.DATE);
		return day;
	}

	/** 查询客户分析 */
	GetCustomerAnalysisList getcustomer;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 查询客户分析 接口
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param timeType
	 * @param categoryType
	 * @author tangxin
	 * @date 2016年12月7日 下午1:59:07
	 */
	private void getCustomerAnalysisList(String timeType, String categoryType) {
		EmmApplication.updateUrl("getCustomerAnalysisList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("timeType", timeType);
		map.put("categoryType", categoryType);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getCustomerAnalysisList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(CustomerAnalysisActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v("content", "content=>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getcustomer = JSONObject.parseObject(resData.toString(), GetCustomerAnalysisList.class);

				if ("1".equals(getcustomer.getResult())) {
					Log.v("获取成功", "");

					if (null != getcustomer && null != getcustomer.getCusAnalysisList()) {
						list.clear();
						list2.clear();
						float number = 0;
						for (int i = 0; i < getcustomer.getCusAnalysisList().size(); i++) {
							number += Float.valueOf(EmmApplication.removed(getcustomer.getCusAnalysisList().get(i)
									.getAnalysisValuePercentage()));
						}
						for (int i = 0; i < getcustomer.getCusAnalysisList().size(); i++) {
							list.add(EmmApplication.isNull(getcustomer.getCusAnalysisList().get(i).getAnalysisValue())?getcustomer.getCusAnalysisList().get(i).getAnalysisValue():"");
							list2.add(Float.valueOf(
									EmmApplication.drop2(""
											+ (Float.valueOf(EmmApplication.removed(getcustomer.getCusAnalysisList()
													.get(i).getAnalysisValuePercentage())) / number) * 100))
									.floatValue());
						}
						if (list.size() <= 0) {
							null_date1.setVisibility(View.VISIBLE);
						} else {
							null_date1.setVisibility(View.INVISIBLE);
							SetSettingChart(0);
							animate();
						}
					} else {
						null_date1.setVisibility(View.VISIBLE);
						EmmApplication.T("获取数据为空");
						list.clear();
						list2.clear();
						SetSettingChart(1);
						animate();
					}
				} else {
					EmmApplication.T(getcustomer.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getcustomer.getErrorCode().toString() + "errorMsg:"
							+ getcustomer.getErrorMsg().toString());
				}
			}
		});
	}

	/**
	 * 查询客户来访分析
	 */
	GetCustomerVisitAnalysisList getcustomervisit;

	/**
	 * 
	 * <p>
	 * <b>Title：</b> 查询客户分析 接口
	 * </p>
	 * <p>
	 * <b>Description：</b>
	 * </p>
	 * 
	 * @param visitTimeType
	 * @author tangxin
	 * @date 2016年12月7日 下午1:59:22
	 */
	private void getCustomerVisitAnalysisList(String visitTimeType) {
		EmmApplication.updateUrl("getCustomerVisitAnalysisList");
		Map<String, String> map = new HashMap<String, String>();
		map.put("version", EmmApplication.getPackageManager(5));
		map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
		map.put("token", EmmApplication.getToken());
		map.put("userId", EmmApplication.getUserId());
		map.put("terminalCode", EmmApplication.getPackageManager(2));
		map.put("projectCode", EmmApplication.getProjectCode());
		map.put("visitTimeType", visitTimeType);
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("params", map);
		JSONObject json = new JSONObject(paramsMap);
		String jsonstr = json.toString();
		RequestParams params = new RequestParams();
		params.put("body", jsonstr);
		Log.v("getCustomerVisitAnalysisList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(Throwable error, String content) {
				super.onFailure(error, content);
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束error:" + error + "==" + content);
			}

			@Override
			public void onFinish() {
				Loading.hideDialogForLoading();
				Log.v(TAG, "请求结束");
				super.onFinish();
			}

			@Override
			public void onStart() {
				super.onStart();
				Loading.hideDialogForLoading();
				Loading.showDialogForLoading(CustomerAnalysisActivity.this, "正在加载...", false, true, 60000);
				Log.v(TAG, "请求开始");
			}

			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				if (content == null) {
					return;
				}
				Log.v("content", "content=>" + content);
				JSONObject jsonObj = JSONObject.parseObject(content);
				JSONObject resData = (JSONObject) jsonObj.get("resData");
				if (resData == null) {
					Log.v(TAG, "信息返回值为空");
					return;
				}

				getcustomervisit = JSONObject.parseObject(resData.toString(), GetCustomerVisitAnalysisList.class);
				if ("1".equals(getcustomervisit.getResult())) {
					Log.v("获取成功", "");
					if (null != getcustomervisit && null != getcustomervisit.getCusVisitAnalysisList()) {
						null_date2.setVisibility(View.INVISIBLE);
						mt.clear();
						pageperature.clear();
						for (int i = 0; i < getcustomervisit.getCusVisitAnalysisList().size(); i++) {
							pageperature.add(getcustomervisit.getCusVisitAnalysisList().get(i)
									.getVisitAnalysisValueNum());
							mt.add(getcustomervisit.getCusVisitAnalysisList().get(i).getVisitAnalysisValue());
						}
						getMax_forMax(pageperature);
					} else {
						null_date2.setVisibility(View.VISIBLE);
						mt.clear();
						pageperature.clear();
						mt.add("");
						pageperature.add("0");
						Max = 10;
						linear.removeAllViews();
					}
				} else {
					null_date2.setVisibility(View.VISIBLE);
					mt.clear();
					pageperature.clear();
					mt.add("");
					pageperature.add("0");
					EmmApplication.T(getcustomervisit.getErrorMsg().toString());
					Log.v("获取失败", "errorCode:" + getcustomervisit.getErrorCode().toString() + "errorMsg:"
							+ getcustomervisit.getErrorMsg().toString());
				}
			}
		});
	}

	// 得最大值
	public void getMax_forMax(ArrayList<String> arr) {
		String maxp = arr.get(0);
		for (int x = 1; x < arr.size(); x++) {
			if (Double.valueOf(maxp).doubleValue() < Double.valueOf(arr.get(x)).doubleValue()) {
				maxp = arr.get(x);
			}
		}
		if (Integer.valueOf(maxp).intValue() < 10)
			Max = 10;
		else
			Max = Integer.valueOf(maxp).intValue() + (int) (Integer.valueOf(maxp).intValue() * 0.3);

		lineView();
		Log.v(TAG, "最大值：" + Max);
	}
}
